package com.backend.demo1.services;

import com.backend.demo1.config.ApiException;
import com.backend.demo1.models.Department;
import com.backend.demo1.models.User;
import com.backend.demo1.mapper.DepartmentMapper;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class DepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;

    public List<Department> getAllDepartments() {
        try {
            return departmentMapper.findAll();
        } catch (Exception e) {
            throw new ApiException(500, "获取部门列表失败: " + e.getMessage());
        }
    }

    public Department getDepartmentById(Long id) {
        try {
            Department department = departmentMapper.findById(id);
            if (department == null) {
                throw new ApiException(404, "部门不存在");
            }
            return department;
        } catch (Exception e) {
            throw new ApiException(500, "获取部门失败: " + e.getMessage());
        }
    }

    public int saveDepartment(Department department) {
        try {
            return departmentMapper.save(department);
        } catch (Exception e) {
            throw new ApiException(500, "保存部门失败: " + e.getMessage());
        }
    }

    public void updateDepartment(Department department) {
        try {
            departmentMapper.update(department);
        } catch (Exception e) {
            throw new ApiException(500, "更新部门失败: " + e.getMessage());
        }
    }

    public void deleteDepartment(Long id) {
        try {
            departmentMapper.deleteById(id);
        } catch (Exception e) {
            throw new ApiException(500, "删除部门失败: " + e.getMessage());
        }
    }

    public List<User> getUsersByDepartmentId(Long departmentId) {
        try {
            return departmentMapper.findUsersByDepartmentId(departmentId);
        } catch (Exception e) {
            throw new ApiException(500, "获取部门用户失败: " + e.getMessage());
        }
    }
}